//加载http核心模块
const fs = require('fs');
let http = require('http');
//使用http自带的方法
//1.创建一个web服务器,返回一个serve实例
let createnew = http.createServer();
//2.当客户端发送了请求，自动触发函数
createnew.on('request', function (request, response) {
    console.log(request.url);
    if (request.url == '/c') {
        fs.readFile('../http/files/one.html', function (err, data) {
            if (err) {
                //设置响应头，解决中文乱码问题
                response.setHeader("Content-Type", "text/plain;charset=utf-8");
                //响应结束输出
                response.end('this file had readed failed');
            } else {
                response.setHeader("Content-Type", "text/html;charset=utf-8");
                response.end(data);
            }
        })
    }
    /*     //Content-Type告诉客户端数据的类型
        response.setHeader('Content-Type', 'text/plain;charset=utf-8') */
    console.log('request has goten');
    console.log('发送的请求网址为' + request.url);
    /*     switch (request.url) {
            case '/plugin':
                response.end('你好');
                break;
            case '/html':
                response.end('<p>明天</p>');
                break;
        } */
    if (request.url == '/a') {
        /*  response.write('你好');
         response.write("world")
         response.end() */
        //简写
        let res = {
            name: "明",
            age: 18,
            sex: "男"
        }
        response.setHeader('Content-Type', 'text/plain;charset=utf-8')
        response.end(JSON.stringify(res))
    } else if (request.url == '/plugin') {
        response.setHeader('Content-Type', 'text/plain;charset=utf-8')
        response.end('你好');
    } else if (request.url == '/html') {//不同的文件，对应不同的类型，比如text/html,text/plugin,可以在oschain在线工具中查找
        response.setHeader('Content-Type', 'text/html;charset=utf-8')
        response.end('<button>明天</button> <a href="#">后天</a>');
    } /* else {
        //response.write('other')
        //response.end() 
        response.end('other list')
    } */
    //response对象中的write方法可以响应数据，可以多次响应，必须用end结束响应，否则一直运行
});
//3.给客户端发送响应消息
createnew.on('response', function () { })
//3.绑定端口号，启动服务器,当从客户端进入该域名时触发请求
createnew.listen(2000, function () {
    console.log('端口已启动，可以通过域名http://127.0.0.1:2000进行访问');
})